package com.fc.campusapplicationsystem.controller;

import com.fc.campusapplicationsystem.model.Area;
import com.fc.campusapplicationsystem.service.AreaService;
import com.fc.campusapplicationsystem.util.ResponseOBJ;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author 贺哲
 * @2020-02-29 15:27
 */
@RestController
@RequestMapping("/areaMapperController")
public class AreaController {
    @Autowired
    AreaService areaService;

    @PostMapping("/add")
    public ResponseOBJ<Integer> add(@RequestBody Area area) {
        ResponseOBJ<Integer> responseOBJ = ResponseOBJ.getInstance();
        try {
            Integer result = areaService.add(area);
            responseOBJ.setData(result);
            responseOBJ.setCode(ResponseOBJ.SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            responseOBJ.setCode(ResponseOBJ.ERROR);
        }
        return responseOBJ;
    }

    @PostMapping("/delete")
    public ResponseOBJ<Integer> delete(@RequestParam("areaId") Integer id) {
        ResponseOBJ<Integer> responseOBJ = ResponseOBJ.getInstance();
        try {
            Integer result = areaService.delete(id);
            responseOBJ.setData(result);
            responseOBJ.setCode(ResponseOBJ.SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            responseOBJ.setCode(ResponseOBJ.ERROR);
        }
        return responseOBJ;
    }

    @GetMapping("/list")
    public ResponseOBJ<List<Area>> list(@RequestParam("page") Integer page,
                                         @RequestParam("limit") Integer limit,
                                         @RequestParam(value = "key", required = false) String key) {
        ResponseOBJ<List<Area>> responseOBJ = ResponseOBJ.getInstance();
        try {
            PageHelper.startPage(page, limit);
            List<Area> areas = areaService.list(key);
            PageInfo<Area> pageInfo = new PageInfo<>(areas);
            responseOBJ.setData(areas);
            responseOBJ.setCount(pageInfo.getTotal());
            responseOBJ.setCode(ResponseOBJ.SUCCESS);
        } catch (Exception e) {
            responseOBJ.setCode(ResponseOBJ.ERROR);
        }
        return responseOBJ;
    }

    @PostMapping("/update")
    public ResponseOBJ<Integer> update(@RequestBody Area area) {
        ResponseOBJ<Integer> responseOBJ = ResponseOBJ.getInstance();
        try {
            Integer result = areaService.update(area);
            responseOBJ.setData(result);
            responseOBJ.setCode(ResponseOBJ.SUCCESS);
        } catch (Exception e) {
            responseOBJ.setCode(ResponseOBJ.ERROR);
        }
        return responseOBJ;
    }
}
